// electron/controller/ProcessController.ts
import { BrowserWindow, ipcMain } from 'electron';
import ProcessService from '../service/ProcessService';
import log from 'electron-log/main';

export const setupProcessIPC = (win: BrowserWindow | null): (() => void) => {
  ipcMain.handle(
    'run-command',
    async (_, command: string, args: string[]) =>
      await ProcessService.run(command, args),
  );

  ipcMain.handle(
    'start-search',
    async (_, device: string, baudrates: string[]) =>
      await ProcessService.startSearch(
        device,
        baudrates,
        (data) => win?.webContents.send('search-output', data),
        (error) => {
          win?.webContents.send('search-error', {
            message: error instanceof Error ? error.message : '未知错误',
            stack: error.stack,
            code: error.code,
            command: 'uio_s',
            args: ['--search', device, '-bs', ...baudrates],
          });
          const firstLine = (error.message || '').split('\n')[0];
          log.error('舵机搜索失败:', firstLine);
        },
      ),
  );

  ipcMain.handle(
    'stop-search',
    async () =>
      await ProcessService.stopSearch((data) =>
        win?.webContents.send('search-output', data),
      ),
  );

  ipcMain.handle(
    'firmware-upgrade-stream',
    async (
      _,
      device: string,
      baudrate: number,
      fileBufferBase64: string,
      servo_id: number,
    ) =>
      await ProcessService.startUpgrade(
        device,
        fileBufferBase64,
        baudrate,
        servo_id,
        (data) => win?.webContents.send('firmware-output', data),
      ),
  );

  return () => {
    ipcMain.removeHandler('run-command');
    ipcMain.removeHandler('start-search');
    ipcMain.removeHandler('stop-search');
    ipcMain.removeHandler('firmware-upgrade-stream');
    log.info('移除相关 IPC 处理器');
  };
};
